package com.netty.tcp.task;

import com.alibaba.fastjson2.JSONObject;
import com.netty.tcp.ew.mapper.ControlCommandLogSystemMapper;
import com.netty.tcp.ew.domain.ControlCommandLogSystem;
import com.netty.tcp.ew.mapper.ControlCommandLogSystemMapper;
import com.netty.tcp.ew.domain.BaseInstruction;
import com.netty.tcp.ew.mapper.BaseInstructionMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;

//import static com.ruoyi.common.utils.SecurityUtils.getCompanyId;
//import static com.ruoyi.common.utils.SecurityUtils.getUsername;

@Component
public class SendMessage {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private Integer port;
    @Value("${spring.redis.password}")
    private String password;

    @Autowired
    private BaseInstructionMapper baseInstructionMapper;

    @Autowired
    private ControlCommandLogSystemMapper controlCommandLogSystemMapper;

    private JedisPool jedisPool;
    private Jedis jedis;


    public String instruction(String imei, String address,Integer operatetype,Integer protoclId){
        String profix = "FE FE FE FE ";//+ translateAddress(address).trim();
        String content = "";
        BaseInstruction baseInstruction = new BaseInstruction();
        ControlCommandLogSystem controlCommandLogSystem = new ControlCommandLogSystem();

        baseInstruction.setInstructionProtoclId(protoclId);
        switch (operatetype) {
            case 0://抄表
                baseInstruction.setInstructionName("抄表");
                List<BaseInstruction> baseInstructionList = baseInstructionMapper.selectBaseInstructionList(baseInstruction);
                if (baseInstructionList.isEmpty() || baseInstructionList.size() == 0) {
                    return "设备指令不完整，无对应的抄表指令！";
                }else{
                    BaseInstruction instruction = baseInstructionList.get(0);
                    content = content + instruction.getInstructionContent();
                    content = content.replace("[1]",translateAddress(address));
                    content = content.replace("[2]",checksum(content.substring(0,content.indexOf("[2]"))));
                    controlCommandLogSystem.setCommandType("抄表");
                }
                break;
            case 1://拉闸
                baseInstruction.setInstructionName("拉闸");
                List<BaseInstruction> baseInstructionList1 = baseInstructionMapper.selectBaseInstructionList(baseInstruction);
                if (baseInstructionList1 !=null || baseInstructionList1.size() == 0) {
                    return "设备指令不完整，无对应的拉闸指令！";
                }else{
                    BaseInstruction instruction = baseInstructionList1.get(0);
                    content = content + instruction.getInstructionContent();
                    content = content.replace("[1]",translateAddress(address));
                    content = content.replace("[2]",checksum(content.substring(0,content.indexOf("[2]"))));
                    controlCommandLogSystem.setCommandType("拉闸");
                }
                break;
            case 2://合闸
                baseInstruction.setInstructionName("合闸");
                List<BaseInstruction> baseInstructionList2 = baseInstructionMapper.selectBaseInstructionList(baseInstruction);
                if (baseInstructionList2!=null || baseInstructionList2.size() == 0) {
                    return "设备指令不完整，无对应的合闸指令！";
                }else{
                    BaseInstruction instruction = baseInstructionList2.get(0);
                    content = content + instruction.getInstructionContent();
                    content = content.replace("[1]",translateAddress(address));
                    content = content.replace("[2]",checksum(content.substring(0,content.indexOf("[2]"))));
                    controlCommandLogSystem.setCommandType("合闸");
                }
                break;
            case 3://清零
                baseInstruction.setInstructionName("清零");
                List<BaseInstruction> baseInstructionList3 = baseInstructionMapper.selectBaseInstructionList(baseInstruction);
                if (baseInstructionList3!=null || baseInstructionList3.size() == 0) {
                    return "设备指令不完整，无对应的清零指令！";
                }else{
                    BaseInstruction instruction = baseInstructionList3.get(0);
                    content = content + instruction.getInstructionContent();
                    content = content.replace("[1]",translateAddress(address));
                    content = content.replace("[2]",checksum(content.substring(0,content.indexOf("[2]"))));
                    controlCommandLogSystem.setCommandType("清零");
                }
                break;
            case 4://查询阀状态
                baseInstruction.setInstructionName("阀控状态查询");
                List<BaseInstruction> baseInstructionList4 = baseInstructionMapper.selectBaseInstructionList(baseInstruction);
                if (baseInstructionList4!=null || baseInstructionList4.size() == 0) {
                    return "设备指令不完整，无对应的清零指令！";
                }else{
                    BaseInstruction instruction = baseInstructionList4.get(0);
                    content = content + instruction.getInstructionContent();
                    content = content.replace("[1]",translateAddress(address));
                    content = content.replace("[2]",checksum(content.substring(0,content.indexOf("[2]"))));
                    controlCommandLogSystem.setCommandType("阀控状态查询");
                }
                break;
            default:
                break;
        }
        this.jedisPool = new JedisPool(new JedisPoolConfig(), host, port,0,password);
        this.jedis =  jedisPool.getResource();
        JSONObject json = new JSONObject();
        json.put("iot_imei",imei);
        json.put("content", profix+content);
        json.put("trytimes",5); //引入重试次数
        this.jedis.rpush("queueName",json.toString());//rpush右入队，lpush左入队
        this.jedis.close();
        controlCommandLogSystem.setCommandTargetdevice(address); //日志目标设备
        controlCommandLogSystem.setCommandContent(content);//日志指令内容
        controlCommandLogSystemMapper.insertControlCommandLogSystem(controlCommandLogSystem);//保存人工操作日志
        return "指令已发送！执行情况以设备执行结果为准！";
    }

    private String translateAddress(String address){
        int l = address.length() / 2;
        String newAddressss = "";
        for (int i = l; i >0; i--) {
            newAddressss = newAddressss + address.substring((i-1) * 2, (i-1) * 2 + 2)+" ";
        }
        return newAddressss.trim();
    }

    /**
     * 计算校验和
     * 传入的字符串是68626623022320681C1035333333348967454E3347773B3A443C9716
     */
    private String checksum(String content)
    {
        content = content.replaceAll("\\s", "");
        Integer length = content.length() / 2;
        Integer summod = 0;
        for(int i = 0;i<length;i++){
            summod += Integer.parseInt(content.substring(i * 2, i * 2 + 2),16);
        }

        String cs = StringUtils.leftPad(Integer.toHexString(summod),4,'0');
        return cs.substring(2,4).toUpperCase();
    }

}
